import React, { useState } from "react";

import * as XLSX from "xlsx";
import "./index.css";
import { NavLink } from "react-router-dom";
// 模拟果币充值记录
type RechargeRecord = {
  id: number;
  username: string;
  storeName: string;
  phoneNumber: string;
  businessDocument: string;
  businessType: string;
  flowType: string;
  time: string;
  amount: number;
};
const mockRechargeRecords: RechargeRecord[] = Array.from(
  { length: 30 },
  (_, index) => ({
    id: index + 1,
    username: `用户${index + 1}`,
    storeName: `店铺${Math.floor(Math.random() * 5) + 1}`,
    phoneNumber: `13${Math.floor(Math.random() * 1000000000)
      .toString()
      .padStart(9, "0")}`,
    businessDocument: `单据${index + 1}`,
    businessType: ["充值", "订单消费", "退款"][Math.floor(Math.random() * 3)],
    flowType: ["收入", "支出"][Math.floor(Math.random() * 2)],
    time: new Date().toISOString(),
    amount: Math.floor(Math.random() * 1000) + 1,
  })
);
// 模拟订单
type Order = {
  id: number;
  status: "待付款" | "已完成" | "全部";
  orderNumber: string;
};
const mockOrders: Order[] = Array.from({ length: 20 }, (_, index) => ({
  id: index + 1,
  status: ["待付款", "已完成", "全部"][Math.floor(Math.random() * 3)],
  orderNumber: `订单${index + 1}`,
}));

const List = () => {
  // 定义充值搜索参数，包括业务类型、店铺名称、手机号码
  const [rechargeSearchParams, setRechargeSearchParams] = useState({
    businessType: "",
    storeName: "",
    phoneNumber: "",
  });
  // 定义过滤后的充值记录
  const [filteredRechargeRecords, setFilteredRechargeRecords] =
    useState<RechargeRecord[]>(mockRechargeRecords);
  // 定义当前页码
  const [rechargeCurrentPage, setRechargeCurrentPage] = useState(1);
  // 定义每页显示的充值记录数
  const rechargeRecordsPerPage = 10;
  // 计算最后一页的索引
  const indexOfLastRechargeRecord =
    rechargeCurrentPage * rechargeRecordsPerPage;
  // 计算第一页的索引
  const indexOfFirstRechargeRecord =
    indexOfLastRechargeRecord - rechargeRecordsPerPage;
  // 计算当前页的充值记录
  const currentRechargeRecords = filteredRechargeRecords.slice(
    indexOfFirstRechargeRecord,
    indexOfLastRechargeRecord
  );
  // 计算总页数
  const totalRechargePages = Math.ceil(
    filteredRechargeRecords.length / rechargeRecordsPerPage
  );
  // 处理充值搜索
  const handleRechargeSearch = () => {
    const { businessType, storeName, phoneNumber } = rechargeSearchParams;
    // 根据搜索参数过滤充值记录
    const newFilteredRecords = mockRechargeRecords.filter((record) => {
      return (
        (businessType === "" || record.businessType === businessType) &&
        (storeName === "" || record.storeName.includes(storeName)) &&
        (phoneNumber === "" || record.phoneNumber.includes(phoneNumber))
      );
    });
    // 更新过滤后的充值记录
    setFilteredRechargeRecords(newFilteredRecords);
    // 重置当前页码
    setRechargeCurrentPage(1);
  };
  // 处理充值下一页
  const handleRechargeNextPage = () => {
    if (rechargeCurrentPage < totalRechargePages) {
      setRechargeCurrentPage(rechargeCurrentPage + 1);
    }
  };
  // 处理充值上一页
  const handleRechargePrevPage = () => {
    if (rechargeCurrentPage > 1) {
      setRechargeCurrentPage(rechargeCurrentPage - 1);
    }
  };

  // 导出充值记录到Excel
  const exportRechargeRecordsToExcel = () => {
    const worksheet = XLSX.utils.json_to_sheet(currentRechargeRecords);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
    XLSX.writeFile(workbook, "recharge - records.xlsx");
  };
  // 直接删除
  const handleRechargeDelete = (id: number) => {
    alert("确认删除");
    const newFilteredRecords = filteredRechargeRecords.filter(
      (record) => record.id !== id
    );
    setFilteredRechargeRecords(newFilteredRecords);
  };
  //  重置
  const handleRechargeReset = () => {
    setRechargeSearchParams({
      businessType: "",
      storeName: "",
      phoneNumber: "",
    });
    setFilteredRechargeRecords(mockRechargeRecords);
  };

  return (
    <div>
      {/* 果币充值部分 */}
      <h2>果币充值记录</h2>
      <div>
        <input
          type="text"
          placeholder="业务类型"
          value={rechargeSearchParams.businessType}
          onChange={(e) =>
            setRechargeSearchParams({
              ...rechargeSearchParams,
              businessType: e.target.value,
            })
          }
        />
        <input
          type="text"
          placeholder="店铺名称"
          value={rechargeSearchParams.storeName}
          onChange={(e) =>
            setRechargeSearchParams({
              ...rechargeSearchParams,
              storeName: e.target.value,
            })
          }
        />
        <input
          type="text"
          placeholder="手机号码"
          value={rechargeSearchParams.phoneNumber}
          onChange={(e) =>
            setRechargeSearchParams({
              ...rechargeSearchParams,
              phoneNumber: e.target.value,
            })
          }
        />
        <button onClick={handleRechargeSearch}>查询</button>
        <button onClick={exportRechargeRecordsToExcel}>导出</button>
        <button onClick={() => handleRechargeReset()}>重置</button>
        <button>
          <NavLink to={"/export"}>查看</NavLink>
        </button>
      </div>
      <table>
        <thead>
          <tr>
            <th>序号</th>
            <th>用户名</th>
            <th>店铺名称</th>
            <th>手机号码</th>
            <th>业务单据</th>
            <th>业务类型</th>
            <th>流水类型</th>
            <th>时间</th>
            <th>果币(元)</th>
            <th>操作</th>
            <th>选择</th>
          </tr>
        </thead>
        <tbody>
          {currentRechargeRecords.map((record, index) => (
            <tr key={record.id}>
              <td>{index + 1}</td>
              <td>{record.username}</td>
              <td>{record.storeName}</td>
              <td>{record.phoneNumber}</td>
              <td>{record.businessDocument}</td>
              <td>{record.businessType}</td>
              <td>{record.flowType}</td>
              <td>{record.time}</td>
              <td>{record.amount}</td>
              <td>
                <button onClick={() => handleRechargeDelete(record.id)}>
                  删除
                </button>
              </td>
              <td></td>
            </tr>
          ))}
        </tbody>
      </table>
      <div>
        <button
          onClick={handleRechargePrevPage}
          disabled={rechargeCurrentPage === 1}
        >
          上一页
        </button>
        <span>
          第 {rechargeCurrentPage} 页，共 {totalRechargePages} 页
        </span>
        <button
          onClick={handleRechargeNextPage}
          disabled={rechargeCurrentPage === totalRechargePages}
        >
          下一页
        </button>
      </div>
    </div>
  );
};

export default List;
